import 'package:app/api/api_repository.dart';
import 'package:app/models/models.dart';
import 'package:app/shared/shared.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AuthController extends GetxController {
  final ApiRepository apiRepository;
  AuthController({required this.apiRepository});

  //  登录控制器
  final GlobalKey<FormState> loginFormKey = GlobalKey<FormState>();
  final loginMobileController = TextEditingController();
  final loginYzmController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  void login(BuildContext context) async {
    if (loginFormKey.currentState!.validate()) {
      final res = await apiRepository.login(LoginRequest(
          mobile: loginMobileController.text, yzm: loginYzmController.text));

      final prefs = Get.find<SharedPreferences>();
      if (res!.data.accessToken.isNotEmpty) {
        prefs.setString(StorageConstants.assess_token, res.data.accessToken);
        Get.offAllNamed('/home');
      }
    }
  }

  @override
  void onClose() {
    super.onClose();

    loginMobileController.dispose();
    loginYzmController.dispose();
  }
}
